package com.qyhl.module_activities.act.player.detail;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qyhl.module_activities.R;
import com.qyhl.module_activities.R2;
import com.qyhl.module_activities.common.ActivityConstant;
import com.qyhl.module_activities.utils.ViewUtils;
import com.qyhl.module_activities.utils.event.PlayerMessageEvent;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.act.ActivityImageBean;
import com.qyhl.webtv.commonlib.entity.act.PlayerVOBean;
import com.qyhl.webtv.commonlib.entity.act.PlayerViewResultBean;
import com.qyhl.webtv.commonlib.entity.act.PlayerWorkVOBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.MShareBoard;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.view.GridDividerItemDecoration;
import com.qyhl.webtv.commonlib.utils.view.imagebrowser.MNImageBrowser;
import com.umeng.socialize.UMShareAPI;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import es.dmoral.toasty.Toasty;

import static com.qyhl.webtv.commonlib.utils.view.video.emptyvideo.EmptyControlVideoActivity.IntentKey_VideoCover;
import static com.qyhl.webtv.commonlib.utils.view.video.emptyvideo.EmptyControlVideoActivity.IntentKey_VideoUrl;


/**
 * 活动详情
 *
 * @author helin
 */
@Route(path = ARouterPathConstant.ACT_PLAYER_DETAIL)
public class PlayerDetailActivity extends BaseActivity implements PlayerDetailContract.PlayerDetailView {
    @BindView(R2.id.votenum)
    TextView votenum;
    @BindView(R2.id.ranking)
    TextView ranking;
    @BindView(R2.id.player_apply_image)
    RoundedImageView mApplyImage;
    @BindView(R2.id.player_results)
    LinearLayout mResultRootView;
    @BindView(R2.id.player_works)
    LinearLayout player_works;
    @BindView(R2.id.player_vote)
    Button player_vote;
    @BindView(R2.id.share)
    ImageView mShare;
    @BindView(R2.id.vid_works)
    RelativeLayout mVideoWorks;
    @BindView(R2.id.works_vid_title)
    TextView mWorksVideoTitle;
    @BindView(R2.id.works_vid_description)
    TextView mWorksDes;
    @BindView(R2.id.player_video_go)
    ImageView mPlayerVideoGo;
    @BindView(R2.id.player_video)
    RoundedImageView mPlayerVideo;
    @BindView(R2.id.pic_works)
    RelativeLayout mPicWorks;
    @BindView(R2.id.imgRecyclerView)
    RecyclerView imgRecyclerView;
    /**
     * 作品集标题
     */
    @BindView(R2.id.works_pic_title)
    TextView mWorksPicTitle;
    /**
     * 图片作品描述
     */
    @BindView(R2.id.works_pic_description)
    TextView mWorksPicDes;

    /**
     * 选手Id
     */
    @Autowired(name = "playerId")
     int mPlayerId;
    /**
     * 报名图
     */
    @Autowired(name = "applyImage")
    String mImage;
    /**
     * 投票状态
     */
    @Autowired(name = "voteStatus")
    int voteStatus;
    /**
     * 活动状态
     */
    @Autowired(name = "actStatus")
    int actStatus;
    /**
     * 控制器
     */
    private PlayerDetailPresenter mPresenter;
    /**
     * 用户信息
     */
    private PlayerVOBean mPlayerDetil;
    /**
     * 作品图
     */
    private List<ActivityImageBean> mPlayerWorkImages;
    /**
     * 活动Id
     */
    @Autowired(name = "actId")
    int mActId;
    /**
     * 当前投票的选手Id
     */
    private Integer mCPlayerId;

    @Autowired(name = "height")
    int mHeight;

    @Autowired(name = "width")
    int mWidth;

    /**
     * 投票标志
     */
    private boolean canVote = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getContentView() {
        return R.layout.act_activity_player_detail;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        if (actStatus == ActivityConstant.STATUS_END || voteStatus == ActivityConstant.VOTE_END) {
            player_vote.setText("投票结束");
            player_vote.setEnabled(false);
        }

        ViewGroup.LayoutParams layoutParams = mApplyImage.getLayoutParams();
        if ( mWidth>mHeight) {
            layoutParams.width = StringUtils.dip2px(this, 180);
            layoutParams.height = StringUtils.dip2px(this, 135);
        } else {
            layoutParams.width = StringUtils.dip2px(this, 112);
            layoutParams.height = StringUtils.dip2px(this, 150);
        }
        mPresenter = new PlayerDetailPresenter(this);
        initView();
    }

    @Override
    protected void setListener() {

    }

    /**
     * 初始化
     */
    private void initView() {
        //封面图
        Glide.with(this)
                .load(mImage)
                .apply(new RequestOptions().error(R.drawable.cover_large_default))
                .into(mApplyImage);

        //点击查看大图
        mApplyImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ArrayList<String> lists = new ArrayList<>();
                lists.add(mImage);
                MNImageBrowser.showImageBrowser(PlayerDetailActivity.this, v, 1, lists);
            }
        });

        //等待动画加载完成获取数据
        mApplyImage.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (PlayerDetailActivity.this != null && !PlayerDetailActivity.this.isFinishing()) {
                    showSimpleLoading();
                    mPresenter.getPlayerDeatil(mPlayerId + "");
                }
            }
        }, 500);

        //分享
        mShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPlayerDetil != null) {
                    MShareBoard shareBoard = new MShareBoard(PlayerDetailActivity.this,String.valueOf(
                            mPlayerDetil.getPlayer().getId()),mPlayerDetil.getPlayer().getPlayerName(),mPlayerDetil.getPlayer().getApplyUrl(),"", CommonUtils.getInstance().getBannerId(),20);
                    shareBoard.showPopupWindow();
//                    ShareUtils.getInstance().goShare(String.valueOf(
//                            mPlayerDetil.getPlayer().getId()),
//                            20,
//                            "",
//                            mPlayerDetil.getPlayer().getPlayerName(),
//                            mPlayerDetil.getPlayer().getApplyUrl(),
//                            PlayerDetailActivity.this);
                }
            }
        });
    }

    @Override
    public void onBackPressed() {
        setResult(555);
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 获取数据失败
     *
     * @param msg
     */
    @Override
    public void onError(String msg) {
        dismissLoading();
        showToast(msg, INFO);
    }

    /**
     * 投票失败
     *
     * @param msg
     */
    @Override
    public void onVoteError(String msg) {
        showToast(msg, INFO);
        canVote = true;
    }

    /**
     * @param data
     */
    @Override
    public void onSuccess(PlayerVOBean data) {
        dismissLoading();
        mPlayerDetil = data;
        showData();
    }

    /**
     * 投票成功
     */
    @Override
    public void voteSuccess() {
        showToast("投票成功", INFO);
        mPlayerDetil.setVoteNumber(mPlayerDetil.getVoteNumber() + 1);
        votenum.setText(mPlayerDetil.getVoteNumber() + "");
        EventBus.getDefault().post(new PlayerMessageEvent("updateAct", mCPlayerId));
        EventBus.getDefault().post(new PlayerMessageEvent("updatePlayerList", mCPlayerId));
        canVote = true;
        ActionLogUtils.getInstance().onEvent(ActionConstant.ACTIVITY_VOTE);
    }

    /**
     * 展示选手数据
     */
    private void showData() {
        votenum.setText(mPlayerDetil.getVoteNumber() + "");
        ranking.setText(mPlayerDetil.getRanking() + "");
        //用户报名表信息
        List<PlayerViewResultBean> results = mPlayerDetil.getResults();
        if (results == null || results.size() == 0) {
            mResultRootView.setVisibility(View.GONE);
        } else {
            for (int i = 0; i < results.size(); i++) {
                View showView = ViewUtils.createShowView(this, results.get(i), mResultRootView);
                if (showView != null) {
                    mResultRootView.addView(showView);
                }
            }
        }
        //作品
        List<PlayerWorkVOBean> works = mPlayerDetil.getPlayerWorksList();
        if (works != null && !works.isEmpty()) {
            player_works.setVisibility(View.VISIBLE);
            for (PlayerWorkVOBean playerWorks : works) {
                if (playerWorks.getPlayerWorks().getType().equals(0)) {
                    createPic(playerWorks);
                } else if (playerWorks.getPlayerWorks().getType().equals(1)) {
                    createVid(playerWorks);
                }
            }
        }
    }

    /**
     * 有视频作品
     */
    private void createVid(final PlayerWorkVOBean playerWorks) {
        mVideoWorks.setVisibility(View.VISIBLE);
        mWorksVideoTitle.setText(playerWorks.getPlayerWorks().getName());
        mWorksDes.setText(playerWorks.getPlayerWorks().getDescription());
        intoImg(playerWorks.getPlayerWorks().getVideoCover(), mPlayerVideo);
        mPlayerVideoGo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString(IntentKey_VideoUrl,playerWorks.getPlayerWorks().getVideoUrl());
                bundle.putString(IntentKey_VideoCover,playerWorks.getPlayerWorks().getVideoCover());

                RouterManager.router(ARouterPathConstant.VIDEO_EMPTY_CONTROL,bundle);

            }
        });
    }

    /**
     * 有图片作品
     */
    private void createPic(PlayerWorkVOBean playerWorks) {
        mPlayerWorkImages = playerWorks.getImages();
        mPicWorks.setVisibility(View.VISIBLE);
        mWorksPicTitle.setText(playerWorks.getPlayerWorks().getName());
        mWorksPicDes.setText(playerWorks.getPlayerWorks().getDescription());
        final List<ActivityImageBean> images = playerWorks.getImages();

        if (images != null && !images.isEmpty()) {
            imgRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
            imgRecyclerView.addItemDecoration(new GridDividerItemDecoration(8, Color.parseColor("#00000000")));

            imgRecyclerView.setAdapter(new CommonAdapter<ActivityImageBean>(this, R.layout.act_playerimg_item, images) {
                @Override
                protected void convert(ViewHolder viewHolder, ActivityImageBean activityImageBean, final int i) {
                    intoImg(images.get(i).getUrl(), viewHolder.getView(R.id.player_img));
                    viewHolder.setOnClickListener(R.id.player_img, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            ArrayList<String> result = new ArrayList<>();
                            for (int i = 0; i < mPlayerWorkImages.size(); i++) {
                                ActivityImageBean pw = mPlayerWorkImages.get(i);
                                if (pw.getId() != -1L) {
                                    result.add(pw.getUrl());
                                }
                            }
                            MNImageBrowser.showImageBrowser(PlayerDetailActivity.this, v, i, result);
                        }
                    });
                }
            });
        }
    }

    private void intoImg(String url, View viewById1) {
        Glide.with(PlayerDetailActivity.this)
                .load(url)
                .apply(new RequestOptions().error(R.drawable.cover_normal_default))
                .into((ImageView) viewById1);
    }

    /**
     * 点击事件
     *
     * @param view
     */
    @OnClick({R2.id.player_vote, R2.id.back})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.player_vote) {
            if (mPlayerDetil == null) {
                return;
            }
            if (canVote) {
                canVote = false;
                //投票
                CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                    @Override
                    public void login(boolean isLogin) {
                        if (isLogin) {
                            if (actStatus == ActivityConstant.STATUS_PROCESSING) {
                                String userName = CommonUtils.getInstance().getUserName();
                                if (voteStatus == ActivityConstant.VOTE_ON) {
                                    mCPlayerId = mPlayerDetil.getPlayer().getId();
                                    mPresenter.vote(mActId, userName, mPlayerDetil.getPlayer().getId());
                                } else if (voteStatus == ActivityConstant.VOTE_OFF) {
                                    onVoteError("投票未开始");
                                } else if (voteStatus == ActivityConstant.VOTE_END) {
                                    onVoteError("投票已结束");
                                }
                            } else if (actStatus == ActivityConstant.STATUS_END) {
                                onVoteError("投票已结束");
                            }
                        } else {
                            Toasty.normal(PlayerDetailActivity.this, "尚未登录或登录已失效").show();
                            RouterManager.routerLogin(PlayerDetailActivity.this, 0);
                            canVote = true;
                        }
                    }

                    @Override
                    public void error(String s) {
                        canVote = true;
                    }
                });

            }

        } else if (i == R.id.back) {
            setResult(555);
            finish();

        } else {
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        ActionLogUtils.getInstance().onResume(this, ActionConstant.PLAYER_DETAIL);
    }

    @Override
    protected void onPause() {
        super.onPause();
        ActionLogUtils.getInstance().onPause(this, ActionConstant.PLAYER_DETAIL);
    }
}
